from passlib.context import CryptContext
import secrets
from jose import jwt

from datetime import datetime, timedelta, timezone
from ..schemas.auth import User, Token
from typing import Union, Dict, Any

from scorpio.core.common.logger import get_logger

logger = get_logger(__name__)



# 配置常量
SECRET_KEY = secrets.token_urlsafe(32)
ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# 模拟数据库
fake_users_db = {
    "admin": {
        "username": "admin",
        "hashed_password": pwd_context.hash("admin")
    }
}

# 创建访问令牌
def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=15))
    to_encode.update({"exp": expire})
    token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    logger.info(f"Access token: {token}")
    return token

# 验证用户
def authenticate_user(username: str, password: str) -> Union[User, bool]:
    logger.info(f"Trying to authenticate user: {username}")
    if username not in fake_users_db:
        logger.info(f"User {username} not found in database")
        return False
    user = User(**fake_users_db[username])
    if not pwd_context.verify(password, user.hashed_password):
        logger.info(f"Password verification failed for user: {username}")
        return False
    logger.info(f"User {username} authenticated successfully")
    return user

# 创建刷新令牌
def create_refresh_token() -> str:
    return secrets.token_urlsafe(64)

def get_jwt_payload(key:str)-> Dict[str, Any]:
    return jwt.decode(key, SECRET_KEY, algorithms=[ALGORITHM])